import { lazyHttpClient } from '@/http';
import { getConfig } from '@/utils';
import type { IApiTDTSearchData, IApiTDTSearchParams, IApiTDTSearchRes } from './types';

const { SM_TIANDITU_TOKEN } = import.meta.env;

/** 逆地理编码查询 */
export const poiSearch = (data: IApiTDTSearchParams) => {
  const params = `{'lon':${data.lng},'lat':${data.lat},'ver':${data.ver || 1}}`;
  const tianditu = getConfig().appSettings.tianditu;
  return lazyHttpClient().get<IApiTDTSearchRes<IApiTDTSearchData>>(
    `${tianditu.url}/geocoder?tk=${SM_TIANDITU_TOKEN}&type=geocode&postStr=${params}`,
    {
      baseURL: '',
    },
  );
};

export const formatPoi = (data?: IApiTDTSearchData, maxLength: number = 40) => {
  const res = { name: '', address: '' };
  if (!data) return res;
  const { formatted_address, addressComponent } = data;
  const { address, county, poi, nation = '' } = addressComponent ?? {};
  res.name = `${county}${poi}`.length > 21 ? poi : `${county}${poi}`;
  if (formatted_address?.length) {
    if (formatted_address?.length <= maxLength && formatted_address?.length) {
      res.address = formatted_address;
    } else if (address?.length + poi?.length <= maxLength && address !== poi) {
      res.address = `${address}${poi}`;
    } else if (address && address.length <= maxLength) {
      res.address = address;
    } else {
      res.address = poi;
    }
  } else {
    res.address = `${nation}${address}`;
  }
  return res;
};
